import React from 'react';
import {FlatList, RefreshControl, StyleSheet, View} from 'react-native';
import {useAsyncStorage} from '@react-native-async-storage/async-storage';
import {useFlatListStore, type DataItem} from '@/store';
import FlatListItem from '@/components/FlatListItem';
import NavigationBar from '@/components/NavigationBar';
import {useFocusEffect} from '@react-navigation/native';

const Favorite = () => {
  const asyncStorage = useAsyncStorage('favorite');
  const store = useFlatListStore();
  const [data, setData] = React.useState<DataItem[]>([]);
  const [loading, setLoading] = React.useState(false);

  useFocusEffect(
    React.useCallback(() => {
      getFlatListData();
    }, []),
  );

  const getFlatListData = () => {
    asyncStorage.getItem().then(value => {
      if (value) {
        setData(JSON.parse(value));
      }
    });
  };

  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      getFlatListData();
      setLoading(false);
    }, 1000);
  };

  const handleUpdate = ({id}: {id: string}) => {
    setData(state => state.filter(item => item.id !== id));
    // 如果最热、趋势里面还有这条数据，联动更新状态（可优化性能）
    const {data1, data2} = store;
    const newData1 = data1.map(item => {
      if (item.id === id) {
        return {
          ...item,
          isSave: !item.isSave,
        };
      }
      return item;
    });
    store.setStore('data1', newData1);
    const newData2 = data2.map(item => {
      if (item.id === id) {
        return {
          ...item,
          isSave: !item.isSave,
        };
      }
      return item;
    });
    store.setStore('data2', newData2);
  };

  return (
    <View style={styles.wrap}>
      <NavigationBar title="收藏" />
      <FlatList<DataItem>
        keyExtractor={item => item.id}
        data={data}
        initialNumToRender={10}
        refreshControl={
          <RefreshControl
            title="加载中..."
            refreshing={loading}
            onRefresh={handleRefresh}
          />
        }
        renderItem={({item, index}) => (
          <FlatListItem
            source="Favorite"
            value={item}
            index={index}
            handleUpdate={handleUpdate}
          />
        )}
      />
    </View>
  );
};

export default Favorite;

const styles = StyleSheet.create({
  wrap: {
    flex: 1,
  },
});
